package xkp.lesson.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxy implements MethodInterceptor {
    //被代理的对象
    private Object object;
    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("代理前....");
        Object result = method.invoke(object,args);
        System.out.println("代理后....");
        return result;
    }

    /**
     * 获取代理对象
     *
     * 注意：JDK中的动态代理，要求业务类必须是接口+实现类的形式
     */
    public Object getProxy(Object object){
        //为目标对象target赋值
        this.object = object;

        Enhancer enhancer = new Enhancer();
        //设置父类,因为Cglib是针对指定的类生成一个子类，所以需要指定父类
        enhancer.setSuperclass(object.getClass());
        //设置回调
        enhancer.setCallback(this);
        //创建并返回代理对象
        Object result = enhancer.create();
        return result;
    }
}
